package com.gpscookie.vocabularystory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import net.youmi.android.AdManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.adview.AdViewLayout;
import com.adview.AdViewManager;
import com.adview.AdViewTargeting;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class BookScreen extends TabActivity implements OnInitListener {
	private ListView list;
	private ArrayList<JSONObject> items;
	private BookListAdapter adapter;
	boolean forceUpdate = false;
	private ArrayList<Book> mybooks;
	private MyBookListAdapter mylistadapter;
	private ListView mylist;
	private String extraURL;
	
	static {
		AdManager.init("6f4d04fa944ff10f", "be1e5a8627231fcd", 30, false, "VS100");
	}	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if (Utils.INSTANCE.tts != null) {
			Log.i("MainScreen:onDestroy():", "TTS is destroied.");
			Utils.INSTANCE.tts.shutdown();
			Utils.INSTANCE.tts = null;
		}		
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabHost th = getTabHost();
        LayoutInflater.from(this).inflate(R.layout.book, th.getTabContentView(), true);
    	LinearLayout tabpublic = (LinearLayout) findViewById(R.id.tabpublic);
        th.addTab(th.newTabSpec(getString(R.string.publicbook))
                .setIndicator(getString(R.string.publicbook))
                .setContent(R.id.tabpublic));

        LinearLayout tabprivate = (LinearLayout) findViewById(R.id.tabprivate);
        th.addTab(th.newTabSpec(getString(R.string.privatebook))
                .setIndicator(getString(R.string.privatebook))
                .setContent(R.id.tabprivate));
        
		LinearLayout layout = (LinearLayout)findViewById(R.id.placeholder);
		//AdViewTargeting.setTestMode(true);
		//AdViewManager.setConfigExpireTimeout(-1);
		AdViewLayout adViewLayout = new AdViewLayout(this, "SDK2011141401020193etbyq1gaum7iz");
		//adViewLayout.setAdViewInterface(this);
		LinearLayout.LayoutParams adViewLayoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		layout.addView(adViewLayout, 0, adViewLayoutParams);
		layout.invalidate();
        
        // check TTS
        Log.i("BookScreen:onCreate():", "check TTS");
        checkTTS();        
        
		forceUpdate = false;
        items = new ArrayList<JSONObject>();
        list = (ListView)findViewById(R.id.booklist);
        adapter = new BookListAdapter(this);
        list.setAdapter(adapter);
        OnItemClickListener listener = new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				try {
					Utils.INSTANCE.currentBook = new Book();
					Utils.INSTANCE.currentBook.setTitle(items.get(pos).getString("title"));
					Utils.INSTANCE.currentBook.setUrl(items.get(pos).getString("url"));
					Utils.INSTANCE.currentBook.setKey(items.get(pos).getString("key"));
					Utils.INSTANCE.currentBook.setTotal(items.get(pos).getInt("total"));
					Utils.INSTANCE.currentBook.setCurrent(1);
					Intent it = new Intent(BookScreen.this, MainScreen.class);
					startActivity(it);
				} catch (JSONException e) {
					Utils.INSTANCE.currentBook = null;
					Toast.makeText(BookScreen.this, getString(R.string.unknownerror), Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
			}};
        list.setOnItemClickListener(listener);
        
        mylist = (ListView)findViewById(R.id.mybooklist);    	
    	mybooks = new ArrayList<Book>();
        mylistadapter = new MyBookListAdapter(this);    	
        mylist.setAdapter(mylistadapter);
        
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	loadPreference();
    	setBusy(true);
    	// check intent
        Intent intent = getIntent();
        String action = intent == null ? null : intent.getAction();
        String dataString = intent == null ? null : intent.getDataString();
        if (null!=intent && null!=action && null!=dataString) {
        	if (dataString.endsWith(".json") && dataString.startsWith("http:")) {
        		Log.i("BookScreen:onResume(): intent data ", dataString);
        		extraURL = dataString;
        	}
        }
        new JSONDownloadTask().execute(Utils.INSTANCE.composeBookListURL());
    }
    
    private class MyBookListAdapter extends BaseAdapter {
    	private Context context;
		private LayoutInflater inflater;
    	
		public MyBookListAdapter(Context c) {
			context = c;
			inflater = LayoutInflater.from(context);
		}    	

		public int getCount() {
			return mybooks.size();
		}

		public Object getItem(int arg0) {
			return mybooks.get(arg0);
		}

		public long getItemId(int arg0) {
			return arg0;
		}

		public View getView(int position, View view, ViewGroup arg2) {
			if (view==null) {
				view = inflater.inflate(R.layout.mybooklistitem, null);
			}
			TextView txt = (TextView)view.findViewById(R.id.txttitle);
			TextView txtNum = (TextView)view.findViewById(R.id.txtnum);
			ImageButton btn = (ImageButton)view.findViewById(R.id.btndelete);
			btn.setTag(new Integer(position));
			txt.setTag(new Integer(position));
			txtNum.setTag(new Integer(position));
			btn.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {					
					Integer pos = (Integer) v.getTag();
					SimpleDBHelper db = new SimpleDBHelper(BookScreen.this);
					db.deleteBook(mybooks.get(pos.intValue()).getKey());
					db.close();
					mybooks.remove(pos.intValue());
					mylistadapter.notifyDataSetChanged();			
				}				
			});
	        txt.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					int pos = (Integer)v.getTag();
					Log.i("......", ""+pos);
					Utils.INSTANCE.currentBook = new Book();
					Utils.INSTANCE.currentBook.setTitle(mybooks.get(pos).getTitle());
					Utils.INSTANCE.currentBook.setUrl(mybooks.get(pos).getUrl());
					Utils.INSTANCE.currentBook.setKey(mybooks.get(pos).getKey());
					Utils.INSTANCE.currentBook.setTotal(mybooks.get(pos).getTotal());
					Utils.INSTANCE.currentBook.setCurrent(1);
					Intent it = new Intent(BookScreen.this, MainScreen.class);
					startActivity(it);				
				}});        
	        txtNum.setOnClickListener(new OnClickListener(){
				public void onClick(View v) {
					int pos = (Integer)v.getTag();
					Log.i("......", ""+pos);
					Utils.INSTANCE.currentBook = new Book();
					Utils.INSTANCE.currentBook.setTitle(mybooks.get(pos).getTitle());
					Utils.INSTANCE.currentBook.setUrl(mybooks.get(pos).getUrl());
					Utils.INSTANCE.currentBook.setKey(mybooks.get(pos).getKey());
					Utils.INSTANCE.currentBook.setTotal(mybooks.get(pos).getTotal());
					Utils.INSTANCE.currentBook.setCurrent(1);
					Intent it = new Intent(BookScreen.this, MainScreen.class);
					startActivity(it);				
				}});
			txt.setText(mybooks.get(position).getTitle());
			txtNum.setText(mybooks.get(position).getCurrent()+"/"+mybooks.get(position).getTotal());
			return view;
		}
    	
    }
    
    private int TTSRTN = 0;
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TTSRTN) {
        	Log.i("MainScreen:onActivityResult():", "TTSRTN"+resultCode);
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {            	
                // success, create the TTS instance
	           	 Utils.INSTANCE.tts = new TextToSpeech(this, this);
            } else {
                // missing data, install it
            	Toast.makeText(this, getString(R.string.ttsdatamissing), Toast.LENGTH_LONG).show();
                Intent installIntent = new Intent();
                installIntent.setAction(
                    TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    	
    }
    
    private void checkTTS() {
    	Log.i("MainScreen:checkTTS():", "start");
    	Intent checkIntent = new Intent();
    	checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    	startActivityForResult(checkIntent, TTSRTN);
    }    
    
    private class BookListAdapter extends BaseAdapter {
    	private Context context;
		private LayoutInflater inflater;
    	
		public BookListAdapter(Context c) {
			context = c;
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return items.size();
		}

		public Object getItem(int position) {
			return items.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View view, ViewGroup parent) {
			if (view==null) {
				view = inflater.inflate(R.layout.booklistitem, null);
			}
			TextView txt = (TextView)view.findViewById(R.id.txttitle);
			TextView txtNum = (TextView)view.findViewById(R.id.txtnum);
			try {
				txt.setText(items.get(position).getString("title"));
				txtNum.setText(items.get(position).getString("total"));
			} catch (JSONException e) {
				txt.setText(getString(R.string.unknownerror));
				e.printStackTrace();
			}
			return view;
		}
    	
    }
    
    private class JSONDownloadTask extends AsyncTask<String, Void, JSONObject> {

		@Override
		protected JSONObject doInBackground(String... params) {
			SimpleDBHelper db = new SimpleDBHelper(BookScreen.this);
			JSONObject json = db.getJSON(params[0], forceUpdate);
			db.close();
			if (extraURL!=null) {
				openWebFile(extraURL);
			}
			return json;
		}
		
		protected void onPostExecute(JSONObject result) {
			if (Utils.INSTANCE.getJSONResultError(result)==0) {
				JSONArray array = Utils.INSTANCE.getJSONResultArray(result);
				if (array!=null) {
					items.clear();
					for (int i=0; i<array.length(); i++) {
						try {
							items.add(array.getJSONObject(i));
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					adapter.notifyDataSetChanged();
				}
			} else {
				Toast.makeText(BookScreen.this, 
						Utils.INSTANCE.getJSONResultMsg(result),
						Toast.LENGTH_LONG).show();
			}
			
	        // get local books        
	        SimpleDBHelper db = new SimpleDBHelper(BookScreen.this);
	        mybooks.clear();
	        db.queryMyBooks(mybooks);
	        db.close();
	        mylistadapter.notifyDataSetChanged();

			setBusy(false);
	    }
	}
    
	public void onInit(int status) {
		if (status==TextToSpeech.SUCCESS) {
		   	int ttsRtn = Utils.INSTANCE.tts.setLanguage(Locale.ENGLISH);
			if (ttsRtn == TextToSpeech.LANG_AVAILABLE || 
				ttsRtn == TextToSpeech.LANG_COUNTRY_AVAILABLE ||
				ttsRtn == TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE) {	        		 
				Toast.makeText(this, getString(R.string.ttsok), Toast.LENGTH_LONG).show();
			} else if (ttsRtn == TextToSpeech.LANG_MISSING_DATA) {
				Toast.makeText(this, getString(R.string.ttsdatamissing), Toast.LENGTH_LONG).show();
				// missing data, install it
		        Intent installIntent = new Intent();
		        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
		        startActivity(installIntent);	        		 
			} else {
				Utils.INSTANCE.tts.shutdown();
				Utils.INSTANCE.tts = null;
				Toast.makeText(this, getString(R.string.ttsfail), Toast.LENGTH_LONG).show();
			}
		} else {
			Utils.INSTANCE.tts.shutdown();
			Utils.INSTANCE.tts = null;
			Toast.makeText(this, getString(R.string.ttsfail), Toast.LENGTH_LONG).show();
		}
	}
	
    private static final int DIALOG_PROGRESS = 0;
	private boolean isBusy = false;
	private Dialog dialog = null;
	private ProgressDialog pdialog = null;
	private final int DIALOG_FILE = 100;
	private TextView txtFile;
	
    @Override
    protected Dialog onCreateDialog(int id) {
    	switch(id) {
			case DIALOG_PROGRESS :
				if (pdialog==null) {
		            pdialog  = new ProgressDialog(this);	            
		            pdialog.setMessage(this.getResources().getText(R.string.loading));
		            pdialog.setIndeterminate(true);
		            pdialog.setCancelable(true);
				}
	            return pdialog;	            
	    	case DIALOG_FILE:
	    		if (dialog==null) {
		    		dialog = new Dialog(this);
		    		dialog.setContentView(R.layout.dialogfile);
		    		dialog.setTitle(getString(R.string.fileopen));
		    		dialog.findViewById(R.id.btnok).setOnClickListener(new OnClickListener() {		    			
		    		    public void onClick(View v) {	    	
		    		    	String path = txtFile.getText().toString();	    	
		    		    	if (null != path && path.length()>0) {
		    		    		BookScreen.this.dismissDialog(DIALOG_FILE);
		    		    		openLocalFile(path);		    		    		
		    		    	}
		    		    }
		    		});
		    		dialog.findViewById(R.id.btncancel).setOnClickListener(new OnClickListener() {
		    		    public void onClick(View v) {
		    		    	BookScreen.this.dismissDialog(DIALOG_FILE);
		    		    }
		    		});
		    		txtFile = (TextView)dialog.findViewById(R.id.fieldpath);
	    		}
	    		File f = Environment.getExternalStorageDirectory();
	    		((TextView)dialog.findViewById(R.id.labelpath)).setText(String.format(getString(R.string.sddpath), f.getAbsoluteFile()));
	    		return dialog;
    	}
    	return null;    	
    }
    
    private void parseJSONBook(JSONObject result) throws JSONException {
		JSONArray array = Utils.INSTANCE.getJSONResultArray(result);
		if (array!=null) {
			// fetch the list and save on the local DB		
			SimpleDBHelper db = new SimpleDBHelper(this);
			// save the book
			Book book = new Book();
			book.setCurrent(1);
			book.setEntry("");
			book.setKey(result.getString("key"));
			book.setTitle(result.getString("title"));
			book.setTotal(result.getInt("total"));
			book.setUrl(result.getString("url"));
			db.saveBook(book);
			for (int i=0; i<array.length(); i++) { 						
				JSONObject row = array.getJSONObject(i);
				String key = row.getString("book");
				String entry = row.getString("entry");
				String url = row.getString("url");
				String shortdesc = row.getString("shortdescription");
				String desc = row.getString("description");		
				String voice = row.getString("voice");
				Entry obj = new Entry();
				obj.setVoice(voice);
				obj.setLevel(-1);
				obj.setKey(key);
				obj.setEntry(entry);
				obj.setUrl(url);
				obj.setShortdesc(shortdesc);
				obj.setDesc(desc);									
				db.saveEntry(obj);	//save on db
				Log.i("...save entry...", entry);
			}// for
			db.close();
		}
    	
    }
    
    private void openWebFile(String path) {
    	SimpleDBHelper db = new SimpleDBHelper(this);
    	JSONObject json = db.getJSON(path, true);
    	db.close();
    	try {
			parseJSONBook(json);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
		}
    }
    
    private void openLocalFile(String path) {
    	if (null!=path && path.startsWith("http:") && path.endsWith("json")) {
    		openWebFile(path);
    		return;
    	}
		File f = new File(Environment.getExternalStorageDirectory()+"/"+path);
		Log.i("...", f.getAbsolutePath());
		setBusy(true);
		try {
			StringBuffer json = new StringBuffer();
			InputStreamReader in = new InputStreamReader(new FileInputStream(f), "utf-8");
			String line = null;
			char[] buf = new char[1024];
			int len = in.read(buf);
			while (len>0) {
				Log.i("...read file...", "");
				json.append(buf, 0, len);
				len = in.read(buf);
			}						
			in.close();
			try {
				JSONObject result = new JSONObject(json.toString());
				parseJSONBook(result);
				mybooks.clear();
				SimpleDBHelper db = new SimpleDBHelper(this);
		        db.queryMyBooks(mybooks);
		        db.close();
		        mylistadapter.notifyDataSetChanged();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
			}
		} catch (IOException e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
		}    
		setBusy(false);
    }

    public boolean isBusy() {
    	return isBusy;
    }
    
    public void setBusy(boolean busy) {
		try {
			if (busy) {
				isBusy = true;
				this.showDialog(DIALOG_PROGRESS);			
			} else {
				isBusy = false;
				this.dismissDialog(DIALOG_PROGRESS);			
			}
		} catch (IllegalArgumentException e) {
			Log.d("AbstractActivity.setBusy", e.toString());
		}    	
    }
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mrefresh:
				setBusy(true);
				forceUpdate = true;
				new JSONDownloadTask().execute(Utils.INSTANCE.composeBookListURL());            	
            	return true;
            case R.id.mopen:
            	BookScreen.this.showDialog(DIALOG_FILE);
            	return true;
            case R.id.msetting:
            	Intent i = new Intent(this, PreferencesFromXml.class);
            	startActivity(i);
            	return true;
        }
        return false;
    }    
    
	protected void loadPreference() {
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		Utils.INSTANCE.cache_life = Integer.parseInt(sp.getString("list_cache", "15"));
		
		TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        Utils.INSTANCE.deviceid = tm.getLine1Number();
        if (Utils.INSTANCE.deviceid==null || Utils.INSTANCE.deviceid.length()==0) {
        	Utils.INSTANCE.deviceid = tm.getDeviceId();
        	if (Utils.INSTANCE.deviceid==null || Utils.INSTANCE.deviceid.length()==0) {
        		Utils.INSTANCE.deviceid = tm.getSimSerialNumber();
        	}
        	if (Utils.INSTANCE.deviceid==null || Utils.INSTANCE.deviceid.length()==0) {
        		Utils.INSTANCE.deviceid = tm.getSubscriberId();
        	}
        	if (Utils.INSTANCE.deviceid==null || Utils.INSTANCE.deviceid.length()==0) {
        		Utils.INSTANCE.deviceid="n/a";
        	}        	
        }
        Log.d("BookScreen:loadPreference: device ID ", Utils.INSTANCE.deviceid);
	}	
    
}